﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Reflection;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Windows.Forms;



namespace ORMAC_Plugin
{
    [RunInstaller(true)]
    public partial class ORMACInstaller : System.Configuration.Install.Installer
    {
        /// <summary>
        /// Class to install the ORMAC plugin
        /// </summary>
        public ORMACInstaller()
        {
            InitializeComponent();
        }
        /// <summary>
        /// Customized install method for ormac object
        /// </summary>
        /// <param name="savedState"></param>
        public override void Install(IDictionary savedState)
        {
            XDocument linqXmlDocument = null;
            string installationPath = Context.Parameters["assemblyPath"];
            installationPath = Path.GetDirectoryName(installationPath);
            string destPath = installationPath + @"\ORMAC_Plugin.AddIn";
            destPath=destPath.Replace(@"\Plugin", "");
            string asmPath = installationPath+@"\ORMAC_Plugin.dll";
            using (FileStream f = new FileStream(destPath, FileMode.Open))
            {
                linqXmlDocument = XDocument.Load(XmlReader.Create(f));
                f.Close();
            }
            var query = from assemblyNode in linqXmlDocument.Descendants()
                        where assemblyNode.Name.LocalName.ToLower().Equals("assembly")
                        select assemblyNode;
            foreach (XElement assemblyNode in query)
            {
                assemblyNode.SetValue(asmPath);
            }
            string addinXml = linqXmlDocument.ToString();
            using (FileStream f = new FileStream(destPath, FileMode.CreateNew|FileMode.Truncate))
            {
                StreamWriter sw = new StreamWriter(f);
                sw.Write(addinXml);
                sw.Flush();
                f.Close();
            }

        }
    }
}
